package com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.robertluozizhao.framecollectdemo.R;
import com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud.adapter.FriendRvAdapter;
import com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud.bean.Friend;
import com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud.bean.FriendTitle;
import com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud.pinyin.CharacterParser;
import com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud.pinyin.PinyinComparator;
import com.example.robertluozizhao.framecollectdemo.activity.test.rongcloud.pinyin.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class NimMainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mSearch;

//    private ListView mListView;
    private RecyclerView mRv;

    private List<Friend> dataLsit = new ArrayList<>();

    private List<Friend> sourceDataList = new ArrayList<>();

    /**
     * 好友列表的 adapter
     */
//    private FriendAdapter adapter;
    private FriendRvAdapter mRvdapter;
    /**
     * 右侧好友指示 Bar
     */
    private SideBar mSidBar;
    /**
     * 中部展示的字母提示
     */
    public TextView dialog;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private List<Object> mRandDate;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_nim_memberlist);
        initView();
        initData();
        if (dataLsit != null && dataLsit.size() > 0) {
            sourceDataList = filledData(dataLsit); //过滤数据为有字母的字段  现在有字母 别的数据没有
        }

        //还原除了带字母字段的其他数据
        for (int i = 0; i < dataLsit.size(); i++) {
            sourceDataList.get(i).setName(dataLsit.get(i).getName());
            sourceDataList.get(i).setType(dataLsit.get(i).getType());
        }

//        dataLsit = null; //释放资源


        // 根据a-z进行排序源数据
//        Collections.sort(sourceDataList, new Comparator<Friend>() {
//            @Override
//            public int compare(Friend o1, Friend o2) {
//                if (o1.getType() > o2.getType()) {
//                    return -1;
//                }else if(o1.getType() < o2.getType()){
//                    return 1;
//                }else {
//                    return 0;
//                }
//            }
//        });

//        Collections.sort(sourceDataList, new Comparator<Friend>() {
//            @Override
//            public int compare(Friend o1, Friend o2) {
//                if (o1.getLetters().equals(o2.getLetters())) {
//                    return o1.getName().compareTo(o2.getName());
//                }else {
//                    return 0;
//                }
//            }
//        });



//        adapter = new FriendAdapter(this, new ArrayList<Friend>());
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mRvdapter = new FriendRvAdapter();
        mRv.setAdapter(mRvdapter);
//        mListView.setAdapter(adapter);

        mSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);

        mRandDate = new ArrayList<>();
        List<Object> qunZhu = new ArrayList<>();
        List<Object> manager = new ArrayList<>();
        List<Object> member = new ArrayList<>();
        List<String> itemFilter=new ArrayList<>();
        for (Friend friend:sourceDataList) {
            if (friend.getType()==2) {
                qunZhu.add(new FriendTitle("群主"));
                qunZhu.add(friend);
            }else if (friend.getType() ==1){
                manager.add(friend);
            }else {
                if (!TextUtils.isEmpty(friend.getLetters())) {
                    if (!itemFilter.contains(friend.getLetters())) {
                        itemFilter.add(friend.getLetters());
                        member.add(new FriendTitle(friend.getLetters()));
                    }
                }
                member.add(friend);
            }
        }
        mRandDate.addAll(qunZhu);//群主在前
        mRandDate.addAll(manager);//管理员其次
        mRandDate.addAll(member);//成员在后

        for (int i = 0; i < mRandDate.size(); i++) {

            if (mRandDate.get(i) instanceof Friend) {
                Friend friend = (Friend) mRandDate.get(i);
                if (friend.getType() ==2) {
//                adapter.mQunzhu.put(randDate.get(i),i);
                    mRvdapter.getMQunzhu().put(friend,i);
                }else if (friend.getType() ==1){
//                adapter.mManager.put(randDate.get(i),i);
                    mRvdapter.getMManager().put(friend,i);
                }else if (friend.getType() ==0){
//                adapter.mMember.put(randDate.get(i),i);
                    mRvdapter.getMMember().put(friend,i);
                    String sortString = friend.getLetters();

//                if (!adapter.letterIndex.containsKey(sortString)) {
//                    adapter.letterIndex.put(sortString,i);
//                }
//                if (!adapter.letterCount.containsKey(sortString)) {
//                    adapter.letterCount.put(sortString,1);
//                }else {
//                    adapter.letterCount.put(sortString,adapter.letterCount.get(sortString)+1);
//                }
                    if (! mRvdapter.getLetterIndex().containsKey(sortString)) {
                        mRvdapter.getLetterIndex().put(sortString,i);
                    }
                    if (!mRvdapter.getLetterCount().containsKey(sortString)) {
                        mRvdapter.getLetterCount().put(sortString,1);
                    }else {
                        mRvdapter.getLetterCount().put(sortString,mRvdapter.getLetterCount().get(sortString)+1);
                    }
                }

            }

        }
        mRvdapter.setList(mRandDate);




//        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Toast.makeText(NimMainActivity.this,String.format(" position:%d name:%s letter:%s",i,randDate.get(i).getName(),randDate.get(i).getLetters()),Toast.LENGTH_SHORT).show();
//            }
//        });

    }

    private void initView() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = PinyinComparator.getInstance();
        mSearch = (EditText) findViewById(R.id.search);
//        mListView = (ListView) findViewById(R.id.listview);
        mRv = (RecyclerView) findViewById(R.id.rv);
        mSidBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        mSidBar.setTextView(dialog);



        //设置右侧触摸监听
        mSidBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {

//
//                if (adapter.letterIndex.containsKey(s)) {
//                    mListView.setSelection(adapter.letterIndex.get(s));
//                }

                if (mRvdapter.getLetterIndex().containsKey(s)) {
//                    mRv.scrollToPosition(0,mRvdapter.getLetterTittle(s));
//                    mRv.smoothScrollToPosition(mRvdapter.getLetterTittle(s));
                    mRvdapter.MoveToPosition(mRv,mRvdapter.getLetterTittle(s));
                }


                //该字母首次出现的位置
//                int position = adapter.getPositionForSection(s.charAt(0));
//                if (position != -1) {
//                    mListView.setSelection(position);
//                }

            }
        });
    }

    private void initData() {
//        dataLsit.add(new Friend("%" + ));

//        for (int i = 0; i < 20; i++) {
//            if (i % 2 == 0) {
//                dataLsit.add(new Friend("阿" + i));
//            } else {
//                dataLsit.add(new Friend("北" + i));
//            }
//        }
//        for (int i = 0; i < 20; i++) {
//            if (i % 2 == 0) {
//                dataLsit.add(new Friend("陈" + i));
//            } else {
//                dataLsit.add(new Friend("杜" + i));
//            }
//        }
//        for (int i = 0; i < 20; i++) {
//            if (i % 2 == 0) {
//                dataLsit.add(new Friend("鹅" + i));
//            } else {
//                dataLsit.add(new Friend("房" + i));
//            }
//        }
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                dataLsit.add(new Friend("高" + i));
            } else {
                dataLsit.add(new Friend("何" + i));
            }
        }
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                dataLsit.add(new Friend("李" + i));
            } else {
                dataLsit.add(new Friend("周" + i));
            }
        }

        Random random = new Random();


        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                dataLsit.add(new Friend(i + "张",0));
            } else {
                dataLsit.add(new Friend( "杨"+i,0));
            }
            if (i==4) {
                dataLsit.add(new Friend( "柠檬"+i,0));
            }
        }
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                dataLsit.add(new Friend("马"+random.nextInt(10),0));
            } else {
                dataLsit.add(new Friend("文"+i,0));
            }
            if (i%3==0){
                dataLsit.add(new Friend("王我"+i,0));
            }
            if (i%4==0){
                dataLsit.add(new Friend("王啊"+i,0));
            }
        }
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                Friend friend = new Friend("早B" + random.nextInt(10));
                friend.setType(1);
                dataLsit.add(friend);
            } else {
                Friend friend = new Friend("不e"+i);
                dataLsit.add(friend);
            }
        }
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                Friend friend = new Friend("说B" + random.nextInt(10));
                friend.setType(1);
                dataLsit.add(friend);
            } else {
                Friend friend = new Friend("啊e"+i);
                dataLsit.add(friend);
            }
        }
        Friend friend = new Friend("宁" + random.nextInt(10),2);
        dataLsit.add(friend);

        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                dataLsit.add(new Friend("@"+i));
            } else {
                dataLsit.add(new Friend("#"+i));
            }
            dataLsit.add(new Friend("^"+i));
        }

    }


    public TextView getDialog() {
        return dialog;
    }

    public void setDialog(TextView dialog) {
        this.dialog = dialog;
    }


    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<Friend> filterDateList = new ArrayList<Friend>();

        if (TextUtils.isEmpty(filterStr)) {
            mRvdapter.setList(mRandDate);
            return;
        } else {
            for (int i = 0; i < mRandDate.size(); i++) {
                if (mRandDate.get(i) instanceof Friend) {
                    Friend friend = (Friend) (mRandDate.get(i));
                    String name = friend.getName();
                    if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                        filterDateList.add(friend);
                    }
                }
            }
//            for (Friend friendModel : sourceDataList) {
//                String name = friendModel.getName();
//                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
//                    filterDateList.add(friendModel);
//                }
//            }
        }

        // 根据a-z进行排序
//        Collections.sort(filterDateList, pinyinComparator);
//        adapter.updateListView(filterDateList);
        mRvdapter.setList(filterDateList);
    }


    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<Friend> filledData(List<Friend> lsit) {
        List<Friend> mFriendList = new ArrayList<Friend>();

        for (int i = 0; i < lsit.size(); i++) {
            Friend friendModel = new Friend();
            friendModel.setName(lsit.get(i).getName());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(lsit.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            /*if (lsit.get(i).getType()==1){
                friendModel.setLetters("管理员");
            } else if(lsit.get(i).getType()==2){
                friendModel.setLetters("全体成员");
            }else */if (sortString.matches("[A-Z]")) {
                friendModel.setLetters(sortString.toUpperCase());
            } else {
                friendModel.setLetters("#");
            }

            mFriendList.add(friendModel);
        }
        return mFriendList;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.re_newfriends:
                Toast.makeText(this, "新朋友页面", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
